﻿using System;
using System.Linq;
using System.IO;
using System.IO.IsolatedStorage;
using System.Collections.Generic;
using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Framework.Client;
using Microsoft.LightSwitch.Presentation;
using Microsoft.LightSwitch.Presentation.Extensions;
using System.Windows.Controls;
using Microsoft.LightSwitch.Threading;

namespace LightSwitchApplication {
    public partial class UserLogin {
        
        partial void UserLogin_Activated() {
            // bind the "Value" of the datacontext to the PasswordBox.
            IContentItemProxy _passwordBox = this.FindControl("PasswordCustomerControl");
            _passwordBox.SetBinding(PasswordBox.PasswordProperty, "Value", System.Windows.Data.BindingMode.TwoWay);
            _passwordBox.ControlAvailable += _passwordBox_ControlAvailable;            
            this.OpenModalWindow("UserLoginModalWindow");
        }

        // the ControlAvailable only fire once. The senond time press enter will not work.
        void _passwordBox_ControlAvailable(object sender, ControlAvailableEventArgs e) {
            PasswordBox pb = e.Control as PasswordBox;
            pb.KeyDown += (s, ea) => {
                if (ea.Key == System.Windows.Input.Key.Enter) {
                    this.PasswordProperty = pb.Password;
                    //ShowMessageBox("the enter key press." + this.PasswordProperty);
                    OkMethod_Execute();
                }
            };
        }
               
        partial void OkMethod_Execute() {
            if (this.PasswordProperty == this.UserProperty.Password) {
                this.Application.CurrentUser = this.UserProperty;
                CloseScreen("UserLogin");
            }
            else {
                string Message = "The password is invalid for the selected user, please enter again.";
                ShowMessageBox(Message);
            }
        }

        partial void CancelMethod_Execute() {
            CloseScreen("UserLogin");
        }

        void CloseScreen(string ScreenName) {
            Dispatchers.Main.BeginInvoke(() => {
                Application.ActiveScreens.Where(p => p.Screen.Name == ScreenName).FirstOrDefault().Close(false);
            });
        }

        void ShowMessageBox(string Message) {
            Dispatchers.Main.BeginInvoke(() =>
            System.Windows.MessageBox.Show(Message)
            );
        }
        
    }
}
